/*  File Name	: ObjectPool.h
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2011-12-20
 *  Description: this is template class,want to use it,
 *  			please include ObjectPool.cpp.
 *  			example:
 *  			1)typedef ObjectPool<MessageBlock> TestPool;
 *  			2)TestPool test_pool;
 *  			3)test_pool.set_malloc_mode(MODE_USE_NEW);
 *  			4)test_pool.set_pool_size(1024);
 *  			5)test_pool.set_pool_name("test");
 */

#ifndef OBJECTPOOL_H_
#define OBJECTPOOL_H_
#include "Header.h"

struct ObjectInfo
{
	ObjectInfo()
	{
		reset();
	}
	int size;
	bool is_used;
	void *data;
	ObjectInfo *next;

	void reset()
	{
		size = 0;
		is_used = false;
		data = NULL;
		next = NULL;
	}
};

/*note:
 * Object must implement reset() method
 */
template<class Object>
class ObjectPool
{
public:
	ObjectPool(int pool_size=4096,int grow_size=256,int object_size=0);

	virtual ~ObjectPool();

	virtual int pop(Object *&obj);

	virtual int push( Object *obj);

	int count_pop(void);

	int count_object(void);

	/*
	 * mode: MODE_USE_NEW-------->use C++ new;
	 * 		 MODE_USE_NEW_SIZE--->use C++ new and specify size
	 *		 MODE_USE_MALLOC ---->use C malloc
	 *
	 * pool_size: max object in this pool
	 * pool_name: pool name
	 */
	void set_malloc_mode(MemMallocMode mode=MODE_USE_NEW);

	void set_pool_size(const int pool_size=1024);

	void set_growth_size(const int size=256);

	void set_pool_name(std::string pool_name="");

	void recycle(void);

protected:
	typedef std::map<int64_t,ObjectInfo*> ObjectMap;

	ObjectMap object_map;

private:
	int mem_malloc(Object *&obj);

	int growth(void);

	std::string pool_name; //对象池的 名字

	int object_count;	//对象池中,对象的总数量

	int pop_count;		//pop出去的对象数量

	int pool_grow_size; //对象池每次增长的对象数量

	int pool_max_size;//池的最大数量

	int object_size;	//对象的大小

	RT_MUTEX rt_mutex;

	ObjectInfo *free_list_head;

	ObjectInfo *free_list_tail;

	MemMallocMode mem_malloc_mode;
};

#include "ObjectPool.cpp"

#endif /* OBJECTPOOL_H_ */


